<template>
	<view class="chat-container">
		<!-- 消息列表区域 -->
		<scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" :scroll-into-view="lastMessageId">
			<view v-for="(message, index) in messages" :key="index" :id="'msg-' + index" class="message-item"
				:class="message.role === 'assistant' ? 'message-left' : 'message-right'">
				<!-- 文件消息 -->
				<view v-if="isFileMessage(message.content)" class="file-message" @click="handleFileClick(message.content)">
					<uni-icons type="file-filled" size="24" color="#666"></uni-icons>
					<text class="file-name">{{ getFileName(message.content) }}</text>
				</view>
				<!-- 文本消息 -->
				<view v-else class="message-bubble">
					{{ message.content }}
				</view>
			</view>
		</scroll-view>

		<!-- 底部输入区域 -->
		<view class="input-area">
			<view class="tool-bar">
				<uni-icons type="folder-add" size="24" color="#666" @click="handleUpload"></uni-icons>
				<uni-icons type="trash-filled" size="24" color="#666" @click="handleClearDialogue"></uni-icons>
			</view>
			<view class="input-box">
				<input type="text" v-model="inputMessage" class="message-input" placeholder="请输入消息" @confirm="sendMessage" />
				<button class="send-button" @click="sendMessage" :disabled="!inputMessage.trim() || loading">发送</button>
			</view>
		</view>

		<gao-ChatSSEClient
			ref="chatSSEClientRef"
			@onOpen="handleOpen"
			@onError="handleError"
			@onMessage="handleMessage"
			@onFinish="handleFinish"
		/>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { dialogueManager } from '@/utils/dialogue.js'
import { http, fileHttp, baseUrl } from '@/utils/http.js'
import { authorization } from '@/utils/authorization.js'
import {onShow} from '@dcloudio/uni-app'

const messages = ref([])
const inputMessage = ref('')
const scrollTop = ref(0)
const lastMessageId = ref('')
const chatSSEClientRef = ref(null)
const loading = ref(false)

// 获取当前时间戳
const getCurrentTimestamp = () => {
	const date = new Date()
	return date.toISOString().split('T')[0] // YYYY-MM-DD 格式
}

// SSE 事件处理函数
const handleOpen = (response) => {
	console.log("SSE连接已打开：", response)
	dialogueManager.clearLastMessage();
}

const handleError = (err) => {
	loading.value = false
	uni.showToast({
		title: '发送失败',
		icon: 'none'
	})
	console.error("SSE错误：", err)
}

const handleMessage = (msg) => {
	console.log("收到消息：", msg)
	// 更新最后一条消息
	dialogueManager.updateLastMessage(msg.data)
	console.log("dialogueManager.getAllDialogues(): ", dialogueManager.getAllDialogues())
	messages.value = dialogueManager.getAllDialogues()
	scrollToBottom()
}

const handleFinish = () => {
	console.log("SSE传输完成")
	loading.value = false
}

// 发送消息
const sendMessage = async () => {
	if (!inputMessage.value.trim() || loading.value) return

	const userMessage = inputMessage.value
	inputMessage.value = ''
	loading.value = true

	// 添加用户消息
	dialogueManager.addMessage('user', userMessage, getCurrentTimestamp())
	messages.value = dialogueManager.getAllDialogues()

	// 添加思考中消息
	dialogueManager.addMessage('assistant', '思考中...', getCurrentTimestamp())
	messages.value = dialogueManager.getAllDialogues()

	// 滚动到底部
	await scrollToBottom()

	// 开始 SSE 聊天
	chatSSEClientRef.value.startChat({
		url: baseUrl + '/aichat/chat',
		headers: {
			Authorization: authorization.getToken()
		},
		method: 'post',
		body: {
			role: 'user',
			content: userMessage,
			timestamp: getCurrentTimestamp()
		}
	})
}

// 判断是否为文件消息
const isFileMessage = (content) => {
	return content.startsWith('file://') || content.startsWith('http://') || content.startsWith('https://')
}

// 获取文件名
const getFileName = (url) => {
	return url.split('/').pop()
}

// 处理文件点击
const handleFileClick = (url) => {
	uni.downloadFile({
		url: url,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.openDocument({
					filePath: res.tempFilePath,
					success: () => {
						console.log('文件打开成功')
					},
					fail: () => {
						uni.showToast({
							title: '文件打开失败',
							icon: 'none'
						})
					}
				})
			}
		},
		fail: () => {
			uni.showToast({
				title: '文件下载失败',
				icon: 'none'
			})
		}
	})
}

// 处理文件上传
const handleUpload = () => {
	uni.chooseFile({
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0]

			try {
				// 上传文件
				const uploadResult = await fileHttp.upload('/file/upload', tempFilePath)
				const fileUrl = JSON.parse(uploadResult).data

				// 添加文件消息
				dialogueManager.addMessage('user', fileUrl, getCurrentTimestamp())
				messages.value = dialogueManager.getAllDialogues()

				// 发送文件路径
				await http.post('/aichat/temp', { path: fileUrl })

				scrollToBottom()
			} catch (error) {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
			}
		}
	})
}

// 滚动到底部
const scrollToBottom = async () => {
	await nextTick()
	lastMessageId.value = `msg-${messages.value.length - 1}`
}

const handleClearDialogue = async () => {
	await http.get("/aichat/clear");
	dialogueManager.clearDialogues();
}

// 初始化
onMounted(() => {
	messages.value = dialogueManager.getAllDialogues()
})

onShow(()=>{
	uni.hideLoading()
});
</script>

<style>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100%;
	/* 设置定位，确保内容不会被状态栏遮挡 */
	/* position: fixed; */
	position: relative;
	/* top: var(--status-bar-height); */
	margin-top: var(--status-bar-height);
	left: 0;
	right: 0;
	/* 设置底部位置，确保不被底部安全区域遮挡 */
	/* bottom: var(--window-bottom); */
	background-color: #f5f5f5;
}

.message-list {
	flex: 1;
	/* 确保消息列表可以正确滚动 */
	/* height: 0; */
	/* height: calc(var(--window-height) - 150px); */
	/* height: calc(100vh - 150px); */
	box-sizing: border-box;
	padding: 20rpx;
	overflow-y: auto;
}

.message-item {
	margin-bottom: 20rpx;
	display: flex;
	flex-direction: column;
}

.message-left {
	align-items: flex-start;
}

.message-right {
	align-items: flex-end;
}

.message-bubble {
	max-width: 70%;
	padding: 20rpx;
	border-radius: 20rpx;
	word-break: break-all;
}

.message-left .message-bubble {
	background-color: #ffffff;
}

.message-right .message-bubble {
	background: linear-gradient(135deg, #668DF8 0%, #4F7CF8 100%);
    color: #ffffff;
}

.file-message {
	display: flex;
	align-items: center;
	background-color: #ffffff;
	padding: 20rpx;
	border-radius: 20rpx;
	max-width: 70%;
}

.file-name {
	margin-left: 10rpx;
	color: #333;
	font-size: 28rpx;
}

.input-area {
	background-color: #ffffff;
	padding: 20rpx;
	border-top: 1rpx solid #eee;
	/* 添加底部安全区域的padding */
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.tool-bar {
	display: flex;
	gap: 20rpx;
	margin-bottom: 10rpx;
}

.input-box {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.message-input {
	flex: 1;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 40rpx;
	padding: 0 30rpx;
	font-size: 28rpx;
}

.send-button {
	background-color: #95EC69;
	color: #333;
	border-radius: 40rpx;
	padding: 0 40rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
}

.send-button[disabled] {
	background-color: #ccc;
	color: #fff;
}
</style>